package org.ank.food;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.channels.FileChannel;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.os.Handler;
import android.os.Message;
import android.util.Log;



public class DBCopier implements Runnable{
	
	public static final int DB_COPY_SUCCESS_CODE = 0;
	public static final int DB_COPY_BEGIN_CODE = 2;
	public static final int DB_COPY_FAIL_CODE = 1;
	Context context;
	Handler handler; 
	Message message;
	
	public DBCopier(Context c, Handler h){
		this.context = c;
		this.handler = h;
	}

	public void run(){
		message = Message.obtain(handler, DB_COPY_BEGIN_CODE);
		message.sendToTarget();
		InputStream input;
		FileOutputStream output;
		ProductDataProvider.DatabaseHelper helper = new ProductDataProvider.DatabaseHelper(context);
		SQLiteDatabase db = helper.getWritableDatabase();
		db.close(); 
		int c;
		byte[] tmp;
		try{
			input = context.getResources().openRawResource(R.raw.products);
			output = new FileOutputStream(ProductDataProvider.DATABASE_LOCATION+
					ProductDataProvider.DATABASE_NAME);
//			//Log.v("DBCopier","flows created. before copying");
			int i=0;
			tmp = new byte[1024];
			while ( (c = input.read(tmp)) != -1 ){
				i++;
				output.write(tmp,0,c);
//				//Log.v("copying",String.valueOf(i));
			}
			//Log.v("DBCopier","finished copying");

			message = Message.obtain(handler, DB_COPY_SUCCESS_CODE);
		}catch(FileNotFoundException e){
			e.printStackTrace();
			//Log.v("DBCopier","Failed to copy - FNF e");
			message = Message.obtain(handler, DB_COPY_FAIL_CODE);
		}catch(IOException e){
			e.printStackTrace();
			//Log.v("DBCopier","Failed to copy - IO e");
			message = Message.obtain(handler, DB_COPY_FAIL_CODE);
		}finally{
			message.sendToTarget();
		}
		
	}

}
